#!/bin/bash

root_dir=$(cd `dirname $0`/.. && pwd -P)
set -e
trap 'catchError $LINENO "$BASH_COMMAND"' ERR # 捕获错误情况
catchError() {
    exit_code=$?
    if [ $exit_code -ne 0 ]; then
        fail "\033[31mcommand: $2\n  at $0:$1\n  at $STEP\033[0m"
    fi
    exit $exit_code
}

notice() {
    echo -e "\033[36m $1 \033[0m "
}
fail() {
    echo -e "\033[41;37m 失败 \033[0m $1"
}

download_url="https://dl.hdslb.com/mobile/fixed/bili_win/bili_win-install.exe"
mkdir -p "$root_dir/cache"
if [[ ! -f "$root_dir/cache/bili_win-install.exe" ]];then
    wget -c "$download_url" -O "$root_dir/cache/bili_win-install.exe.tmp"
    mv "$root_dir/cache/bili_win-install.exe.tmp" "$root_dir/cache/bili_win-install.exe"
fi
tmp_dir="$root_dir/tmp"
mkdir -p "$tmp_dir/bili"

notice "一次版本校验"
BILIBILI_VERSION=$(exiftool -S -ProductVersionNumber "$root_dir/cache/bili_win-install.exe")
BILIBILI_VERSION=(${BILIBILI_VERSION//: / })
BILIBILI_VERSION=${BILIBILI_VERSION[1]}
CONF_VERSION=$(cat "$root_dir/conf/bilibili_version")
if [[ "$BILIBILI_VERSION" != "$CONF_VERSION" ]];then
  fail "下载的版本与配置的版本不匹配！！！$BILIBILI_VERSION != $CONF_VERSION"
  exit 1
fi

7z x -y "$root_dir/cache/bili_win-install.exe" -o"$tmp_dir/bili" "\$PLUGINSDIR/app-64.7z"
7z x -y "$tmp_dir/bili/\$PLUGINSDIR/app-64.7z" -o"$tmp_dir/bili" "resources"
rm -rf "$tmp_dir/bili/\$PLUGINSDIR/app-64.7z" "$tmp_dir/bili/resources/elevate.exe"

# cd "$tmp_dir/bili/resources"
# asar e app.asar app

# notice "二次版本校验"
# BILIBILI_VERSION=$(grep -Pa 'version": "\d+\.\d+\.\d' -o  app/package.json | sed 's/version": "//')
# CONF_VERSION=$(cat "$root_dir/conf/bilibili_version")
# if [[ "$BILIBILI_VERSION" != "$CONF_VERSION" ]];then
#   fail "下载的版本与配置的版本不匹配！！！"
#   exit 1
# fi
# rm -rf app

rm -rf "$root_dir/app"
mkdir -p "$root_dir/app"

if [[ -d "$root_dir/electron/resources" && ! -f "$root_dir/electron/resources/app-update.yml" ]];then
  cd "$root_dir/electron/resources" && ln -s "../../app/app-update.yml" app-update.yml
fi
